package com.eastfair.venueservice.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.UserAccountDto;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.exception.BizException;
import com.eastfair.echo.core.EchoService;
import com.eastfair.venueservice.dto.*;
import com.eastfair.venueservice.entity.ServiceProviderUser;
import com.eastfair.venueservice.service.ServiceProviderService;
import com.eastfair.venueservice.service.ServiceProviderUserService;
import com.eastfair.venueservice.vo.ServiceProviderUserVO;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 服务商用户关系
 * </p>
 *
 * @author dqq
 * @date 2023-02-02
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/serviceProviderUser")
@Api(value = "ServiceProviderUser", tags = "服务商用户关系")
@PreAuth(replace = "venueservice:serviceProviderUser:")
public class ServiceProviderUserController extends SuperController<ServiceProviderUserService, Long, ServiceProviderUser, ServiceProviderUserPageQuery, ServiceProviderUserSaveDTO, ServiceProviderUserUpdateDTO> {

    @Resource
    private EchoService echoService;

    @Resource
    private ServiceProviderUserService serviceProviderUserService;


    @Resource
    private ServiceProviderService serviceProviderService;

    @Resource
    UserAccountServiceFeign userAccountServiceFeign;

    @Override
    public void handlerResult(IPage<ServiceProviderUser> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<ServiceProviderUser> serviceProviderUserList = list
                .stream()
                .map((map) -> ServiceProviderUser.builder().build())
                .collect(Collectors.toList());
        return R.success(baseService.saveBatch(serviceProviderUserList));
    }

    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ServiceProviderUserPageQuery> params) {
        ServiceProviderUserPageQuery pageQuery = params.getModel();
    }

    /**
     * 用户ID批量获取服务商用户关系.
     *
     * @param query the query
     * @return the r
     */
    @PostMapping("/userIds/query")
    public R<List<ServiceProviderUserVO>> queryByUserIds(@RequestBody ServiceProviderUserDTO query) {
        log.info("queryByUserIds - 用户ID批量获取服务商用户关系, query={}", query);
        return R.successDef(serviceProviderUserService.listVOByIds(query.getUserIdList(),
                query.getServiceProviderId(), query.getServiceProviderType()));
    }

    /**
     * 保存服务商，用户关系.
     *
     * @param serviceProviderUserDTO the service provider user dto
     * @return the r
     */
    @PostMapping("/save")
    public R<Boolean> save(@RequestBody ServiceProviderUserDTO serviceProviderUserDTO) {
        log.info("save - 保存服务商，用户关系, serviceProviderUserDTO={}", serviceProviderUserDTO);
        return R.successDef(serviceProviderUserService.saveServiceProviderUser(serviceProviderUserDTO));
    }

    /**
     * 移除用户，服务商关系.
     *
     * @param userId              the user id
     * @param serviceProviderId   the service provider id
     * @param serviceProviderType the service provider type
     * @return the r
     */
    @GetMapping("/delete")
    public R<Boolean> remove(@RequestParam("userId") Long userId,
                             @RequestParam("serviceProviderId") Long serviceProviderId,
                             @RequestParam("serviceProviderType") String serviceProviderType) {
        log.info("remove - 移除用户，服务商关系, userId={}, serviceProviderId={}, serviceProviderType={}", userId, serviceProviderId, serviceProviderType);
        return R.successDef(serviceProviderUserService.removeServiceProviderUser(userId, serviceProviderId, serviceProviderType));
    }

    /**
     * 批量移除用户，服务商关系.
     *
     * @param serviceProviderUserDTO the service provider user dto
     * @return the r
     */
    @PostMapping("/batch/delete")
    public R<Boolean> removeBatch(@RequestBody ServiceProviderUserDTO serviceProviderUserDTO) {
        log.info("removeBatch - 批量移除用户，服务商关系, serviceProviderUserDTO={}", serviceProviderUserDTO);
        return R.successDef(serviceProviderUserService.removeServiceProviderUser(serviceProviderUserDTO.getUserIdList(),
                serviceProviderUserDTO.getServiceProviderId(), serviceProviderUserDTO.getServiceProviderType()));
    }


    /**
     * 查询待同步cms的组织用户关系.
     *
     * @return the r
     */
    @ApiOperation("查询待同步cms的组织用户关系")
    @GetMapping("/cms/sync")
    public R<List<ServiceProviderUserVO>> queryForCmsUserSync() {
        log.info("queryForCmsSync - 查询待同步cms的服务商");
        try {
            List<ServiceProviderUserVO> serviceProviderUserVOList = serviceProviderUserService.listWaitCmsUserSync();
            //组装公司社会编码
            if (CollectionUtil.isNotEmpty(serviceProviderUserVOList)) {
                List<Long> serviceProviderIdList = serviceProviderUserVOList.stream().map(ServiceProviderUserVO::getServiceProviderId).collect(Collectors.toList());
                ServiceProviderDTO serviceProviderDTO = new ServiceProviderDTO();
                serviceProviderDTO.setIds(serviceProviderIdList);
                List<ServiceProviderVO> serviceProviderVOList = serviceProviderService.listServiceProviderVOs(serviceProviderDTO);
                if (CollectionUtil.isNotEmpty(serviceProviderVOList)) {
                    for (ServiceProviderUserVO serviceProviderUserVO : serviceProviderUserVOList) {
                        for (ServiceProviderVO serviceProviderVO : serviceProviderVOList) {
                            if (serviceProviderVO.getId().equals(serviceProviderUserVO.getServiceProviderId())) {
                                serviceProviderUserVO.setUscc(serviceProviderVO.getUscc());
                            }
                        }
                    }
                }


                //组装用户身份证号
                UserAccountDto userAccountDto = new UserAccountDto();
                List<Long> userIdList = serviceProviderUserVOList.stream().map(ServiceProviderUserVO::getUserId).collect(Collectors.toList());
                userAccountDto.setUserIds(userIdList);
                R<List<UserAccountVo>> listR = userAccountServiceFeign.querySimpleByIds(userAccountDto);
                if (listR.getIsSuccess()) {
                    List<UserAccountVo> userAccountVoList = listR.getData();
                    if (CollectionUtil.isNotEmpty(userAccountVoList)) {
                        for (ServiceProviderUserVO serviceProviderUserVO : serviceProviderUserVOList) {
                            for (UserAccountVo userAccountVo : userAccountVoList) {
                                if (userAccountVo.getId().equals(serviceProviderUserVO.getUserId())) {
                                    serviceProviderUserVO.setCardNumber(userAccountVo.getIdCard());
                                }
                            }
                        }
                    }
                }

            }
            return R.successDef(serviceProviderUserVOList);
        } catch (BizException e) {
            return R.fail(e);
        }
    }


    /**
     * .
     * 更新组织用户已同步
     *
     * @return the r
     */
    @ApiOperation("更新组织用户已同步")
    @PostMapping("/cms/updSync")
    public R updForCmsUserSyncupdSync(@RequestBody ServiceProviderUserDTO serviceProviderUserDTO) {
        log.info("queryForCmsSync - 更新组织用户已同步");
        try {
            List<ServiceProviderUser> serviceProviderUserList = serviceProviderUserService.listServiceProviderUser(serviceProviderUserDTO);
            if (CollectionUtil.isNotEmpty(serviceProviderUserList)) {
                for (ServiceProviderUser serviceProviderUser : serviceProviderUserList) {
                    serviceProviderUser.setCmsSync(BusinessConstant.YES);
                }
                serviceProviderUserService.updateBatchById(serviceProviderUserList);
            }
            return R.success();
        } catch (BizException e) {
            return R.fail(e);
        }
    }
}
